<?php

function TPL($file, $data = null, $cache = true) {
    $smarty = new Smarty();
    if ($data != null) {
        foreach ($data as $key => $value) {
            $smarty->assign($key, $value);
        }
    }
    $smarty->setTemplateDir(__DIR__ . '/smarty/templates');
    $smarty->setCompileDir(__DIR__ . '/smarty/templates_c');
    $smarty->setCacheDir(__DIR__ . '/smarty/cache');
    $smarty->setConfigDir(__DIR__ . '/smarty/configs');
    $mod = (($cache) ? "string" : "eval");
    ob_start();
    if (is_file($file)) {
        $smarty->display($mod . ":" . file_get_contents($file));
    } else {
        $smarty->display($mod . ":" . $file);
    }
    $html = str_replace(array("\r", "\n"), "", ob_get_contents());
    ob_end_clean();
    return $html;
}

function Smarty($file, $data = null, $cache = true) {
    return TPL($file, $data, $cache);
}

function Template($file, $data = null, $cache = true) {
    return TPL($file, $data, $cache);
}

function importPHP($nome) {
    pkj_importPHP($nome);
}

function pkj_importPHP($nome) {
    include conf::$pkjHome . '/php/' . $nome . '/' . $nome . '.php';
}

function pkj_import($elemento) {
    import($elemento);
}

/**
 * Coloque essa fun��o dentro 
 * @param type $elemento Pode variar conforme o que vai importar
 * jquery = jquery
 * marcara = jquery mask e jquery maskmoney
 * webcam = jquery webcam
 * slider = nivo slider
 * tema = tema da 99lime kickstart
 * movel = jquery mobile
 */
function import($elemento) {
    $base = conf::$pkjHome;
    switch ($elemento) {
        case "all":
            import("jquery");
            import("tema");
            import("ui");
            import("bind");
            import("table");
            import("tiny");
            import("combo");
            break;
        case "jquery":
            echo "<script type='text/javascript' src='" . $base . "/jquery-1.8.2.js' ></script>";
            echo "<script type='text/javascript' src='" . $base . "/mask.js' ></script><script type='text/javascript' src='" . $base . "/maskMoney.js' ></script>";
            echo "<script type='text/javascript' src='" . $base . "/util.js' ></script>";
            echo "<script type='text/javascript' src='" . $base . "/jquery.bpopup.min.js' ></script>";
            echo "<link rel='stylesheet' href='" . $base . "/popup.css' >";
            break;
        case "ui":
            echo "<script type='text/javascript' src='" . $base . "/ui/js.js' ></script><link rel='stylesheet' href='" . $base . "/ui/css.css' >";
            break;
        case "combo":
            echo "<script type='text/javascript' src='" . $base . "/chosen/js.js' ></script>";
            echo "<link rel='stylesheet' href='" . $base . "/chosen/css.css' >";
            echo "<script type='text/javascript'>jQuery(document).ready(function() { $('select').chosen(); });</script>";
            break;
        case "table":
            echo "<script type=\"text/javascript\" src=\"{$base}/media/js/jquery.dataTables.min.js\" ></script>
                  <link rel=\"stylesheet\" href=\"{$base}/media/css/jquery.dataTables.min.css\" />
                  <script src=\"{$base}/extensions/TableTools/js/dataTables.tableTools.min.js\" type=\"text/javascript\"></script>
                  <link href=\"{$base}/extensions/TableTools/css/dataTables.tableTools.min.css\" rel=\"stylesheet\" type=\"text/css\"/>";
            echo "<script  type=\"text/javascript\">$(document).ready(function() { $('table').DataTable({dom: 'T<\"clear\">lfrtip',tableTools: {\"sSwfPath\": \"{$base}/swf/copy_csv_xls_pdf.swf\" }});});</script>";
            break;
        case "webcam":
            echo "<script type='text/javascript' src='" . $base . "/as3/jquery.webcam.as3.js' ></script>";
            break;
        case "slider":
            echo "<script type='text/javascript' src='" . $base . "/slider/jquery.nivo.slider.js' ></script><link rel='stylesheet' href='" . $base . "/slider/nivo-slider.css' ><link rel='stylesheet' href='" . $base . "/slider/themes/default/default.css' >";
            break;
        case "tema":
            echo "<script type='text/javascript' src='" . $base . "/tema/js/kickstart.js' ></script><link rel='stylesheet' href='" . $base . "/tema/css/kickstart.css' >";
            break;
        case "movel":
            echo "<script type='text/javascript' src='" . $base . "/mobile/jquery.mobile-1.4.5.min.js' ></script><link rel='stylesheet' href='" . $base . "/mobile/jquery.mobile.structure-1.4.5.min.css' ><link rel='stylesheet' href='" . $base . "/mobile/jquery.mobile.theme-1.4.5.min.css' ><link rel='stylesheet' href='" . $base . "/mobile/jquery.mobile.external-png-1.4.5.min.css' ><link rel='stylesheet' href='" . $base . "/mobile/jquery.mobile.theme-1.4.5.min' >";
            break;
        case "tiny":
//            echo "<script type='text/javascript' src='" . $base . "/tiny/tiny_mce.js' ></script>";
            ?>
            <script src="<?php echo $base ?>/tinymce/tinymce.min.js" ></script>
            <script type="text/javascript">
                tinymce.init({
                    selector: "textarea",
                    language: 'pt_BR',
                    theme: "modern",
                    plugins: [
                        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                        "searchreplace wordcount visualblocks visualchars code fullscreen",
                        "insertdatetime media nonbreaking save table contextmenu directionality",
                        "emoticons template paste textcolor colorpicker textpattern"
                    ],
                    toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
                    toolbar2: "print preview media | forecolor backcolor emoticons | responsivefilemanager",
                    image_advtab: true,
                    convert_urls: false,
                    setup: function (editor) {
                        editor.on('change', function () {
                            tinymce.triggerSave();
                        });
                    },
                    external_filemanager_path: "<?php echo $base ?>/filemanager/",
                    filemanager_title: "Responsive Filemanager",
                    external_plugins: {"filemanager": "<?php echo $base ?>/filemanager/plugin.min.js"}
                });
            </script>
            <?php
            break;
        case "bind":
//            $conteudo = file_get_contents($base . "/bind.min.js");
            echo '<script type="text/javascript" src="' . $base . "/bind.js" . '"></script>';
            break;
        default:
            echo "<script type='text/javascript' >alert('Não entendi :(');</script>";
            break;
    }
}

function pkj_webcamHTML($id) {
    webcamHTML($id);
}

function webcamHTML($id) {
    echo "<div style='width: 640px;height: 480px;overflow;auto;' id='$id'>";
}

function pkj_webcamJS($id) {
    webcamJS($id);
}

function webcamJS($id) {
    $base = conf::$pkjHome;
    $valor = "  
   $('#$id').webcam({
     swffile: '" . $base . "pkj/as3/sAS3Cam.swf',
     previewWidth: 640,
     previewHeight: 480,

     resolutionWidth: 640,
     resolutionHeight: 480,
     cameraEnabled:  function () {
      var cameraApi = this;
      setTimeout(function() { cameraApi.setCamera(0); }, 200);      
     }    
    }); 
";
    echo $valor;
}

function pkj_sliderHTML($id, $imagens) {
    sliderHTML($id, $imagens);
}

function sliderHTML($id, $imagens, $altura = "") {
    $ret = "";
    $style = "";
    if ($altura != ""):
        $style = "height: $altura !important;";
    endif;
    $ret .= "<div class='slider-wrapper theme-default' style='$style'><div id='$id' class='nivoSlider' style='$style'>";
    for ($index = 0; $index < count($imagens); $index++) {
        $ret .= "<img src=" . $imagens[$index] . " style='$style'/>";
    }
    $ret .= "</div></div>";
    return $ret;
}

function pkj_sliderJS($id) {
    pkj_sliderJS($id);
}

function sliderJS($id) {
    return "$('#$id').nivoSlider();\n";
}

function form($nomes, $textos = array()) {
    for ($index = 0; $index < count($nomes); $index++) {
        echo "<div class='col_2' style='height:32px'>";
        if (isset($textos[$index])) {
            echo $textos[$index];
        } else {
            echo strtoupper(substr($nomes[$index], 0, 1)) . substr($nomes[$index], 1);
        }
        echo "</div>";
        echo "<div class='col_10' style='height:32px'>";
        //echo find($nomes[$index], "<");
        if (find($nomes[$index], "<") >= 1) {
            echo $nomes[$index];
        } else {
            echo "<input type='" . (($nomes[$index] == "senha") ? "password" : "text") . "' style='width:100%;' name='$nomes[$index]' id='$nomes[$index]' />";
        }
        echo "</div>";
    }
}

function formLine($nomes, $textos = array()) {
    $nulos = 0;
    foreach ($textos as $value) {
        if ($value == "") {
            $nulos++;
        }
    }
    $menor = intval((24 / count($nomes)) * 0.4);
    $maior = intval((24 / count($nomes)) * 0.8);
    for ($index = 0; $index < count($nomes); $index++) {
        if (isset($textos[$index])) {
            if ($textos[$index] != "") {
                echo "<div class='col_{$menor}' style='height:32px'>";
                echo $textos[$index];
                echo "</div>";
            }
        } else {
            if ($nomes[$index] != "") {
                echo "<div class='col_{$menor}' style='height:32px'>";
                echo strtoupper(substr($nomes[$index], 0, 1)) . substr($nomes[$index], 1);
                echo "</div>";
            }
        }
        if ($index == count($nomes) - 1):
            $val = $maior + $nulos;
        else:
            $val = $maior;
        endif;
        echo "<div class='col_{$val}' style='height:32px'>";
        if (find($nomes[$index], "<") >= 1) {
            echo $nomes[$index];
        } else {
            echo "<input type='" . (($nomes[$index] == "senha") ? "password" : "text") . "' style='width:100%;' name='$nomes[$index]' id='$nomes[$index]' />";
        }
        echo "</div>";
    }
}

function pkj_utf8_encode($lista) {
    return utf8_array_encode($lista);
}

function utf8_array_encode($array) {
    utf8_encode_deep($array);
    return $array;
}

function utf8_encode_deep(&$input) {
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else if (is_array($input)) {
        foreach ($input as &$value) {
            utf8_encode_deep($value);
        }

        unset($value);
    } else if (is_object($input)) {
        $vars = array_keys(get_object_vars($input));

        foreach ($vars as $var) {
            utf8_encode_deep($input->$var);
        }
    }
}

function encodeTxt($var) {
    $string = $var;
    $a = "��������������������������������������������������������������??";
// Primeiro na variavel $a coloco todas as letras e os tipos de acentos que quero remover.
    $b = "aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr";
// Depois disso na variavel $b coloco na mesma ordem por qual eu vou substituir.
    $string = utf8_decode($string);
//Aqui eu pego a string e coverto para ISO-8859-1.
    $string = strtr($string, utf8_decode($a), $b); //substitui letras acentuadas por "normais"
    $string = trim($string); // retira espaco
    $string = strtolower($string); // passa tudo para minusculo
    return utf8_encode($string); //finaliza, gerando uma sa�da para a funcao
}

function img64($base64, $id = "imgpkj", $style = "", $ext = "") {
    return "<img src='data:image" . ((empty($ext)) ? "" : "/{$ext}") . ";base64,{$base64}' id='$id' " . ((!empty($style)) ? "style='{$style}'" : "" ) . " />";
}

function pkj_camposSequencia($campos) {
    $camposSequencia = "";
    for ($index = 0; $index < count($campos); $index++) {
        if ($index == count($campos) - 1) {
            $camposSequencia .= $campos[$index];
        } else {
            $camposSequencia .= $campos[$index] . ",";
        }
    }
    return $camposSequencia;
}

function pkj_camposSet($campos) {
    $camposSet = "";
    for ($index = 0; $index < count($campos); $index++) {
        if ($index == count($campos) - 1) {
            $camposSet .= $campos[$index] . " = ?";
        } else {
            $camposSet .= $campos[$index] . " = ?,";
        }
    }
    return $camposSet;
}

function pkj_interrogacao($qtd) {
    $i = "";
    for ($index = 0; $index < $qtd; $index++) {
        if ($index == $qtd - 1) {
            $i .= "?";
        } else {
            $i .= "?,";
        }
    }
    return $i;
}

function pkj_parametros($campos) {
    $total = '$parametros = array(';
    for ($index = 0; $index < count($campos); $index++) {
        if ($index == count($campos) - 1) {
            $total .= '$this->' . $campos[$index];
        } else {
            $total .= '$this->' . $campos[$index] . ",";
        }
    }
    $total .= ');' . "\n";
    return $total;
}

function pkj_gerarClasse($tabela, $campos) {
    $total = "<?php \n";
    $camposSemID = $campos;
    unset($camposSemID[0]);
    rsort($camposSemID);
    $total .="class " . strtoupper(substr($tabela, 0, 1)) . strtolower(substr($tabela, 1)) . " {\n";
    foreach ($campos as $value) {
        $total .= 'public $' . $value . ";\n";
    }
    //insert
    $total .= "public function insert(" . '$parametros=array()' . "){\n";
    $total .= '$sql = "' . "insert into $tabela (" . pkj_camposSequencia($camposSemID) . ") values(" . pkj_interrogacao(count($camposSemID)) . ")" . '";' . "\n";
    $total .= 'if(count($parametros) < 1){';
    $total .= pkj_parametros($camposSemID);
    $total .= "}\n";
    $total .= 'pkj_query($sql,$parametros);' . "\n";
    $total .= "}\n";
    //update
    $total .= "public function update(" . '$where = "",$parametro = ""' . "){\n";
    $IDDepois = $camposSemID;
    $IDDepois[] = "id";
    $total .= '$sql = "update ' . $tabela . " set " . pkj_camposSet($camposSemID) . '".((!empty($where))?" where {$where}":"");' . "\n";
    $total .= 'if(!is_array($parametro)){' . "\n";
    $total .= pkj_parametros($IDDepois);
    $total .= "}else{\n";
    $total .= '$parametros[] = $parametro;' . "\n";
    $total .= '}' . "\n";
    $total .= 'pkj_query($sql,$parametros);' . "\n";
    $total .= "}\n";

    $total .= "public function select(" . '$where = "",$parametros = ""' . "){\n";
    $total .= '$sql = "select * from ' . $tabela . '".((!empty($where))?" where {$where}":"");' . "\n";
    $total .= 'if (!is_array($parametros)){ $query = pkj_executa($sql); }else{ $query = pkj_executa($sql, $parametros); }' . "\n";
    $total .= '$arquivos = array();' . "\n";
    $total .= '$contador = 0;' . "\n";
    $total .= 'foreach ($query as $value) {' . "\n";
    $total .= '  $arquivos[$contador] = new ' . strtoupper(substr($tabela, 0, 1)) . strtolower(substr($tabela, 1)) . '();' . "\n";
    foreach ($campos as $value) {
        $total .= '  $arquivos[$contador]->' . $value . ' = $value["' . $value . '"];' . "\n";
    }
    $total .= '  $contador++;' . "\n";
    $total .= "  }\n";
    $total .= 'return $arquivos;' . "\n";
    $total .= "}\n";

    $total .= "public function delete(" . '$where = "",$parametros = ""' . "){\n";
    $total .= '$sql = "delete from ' . $tabela . '".((!empty($where))?" where {$where}":"");' . ";\n";
    $total .= '$parametros = array($this->id)' . ";\n";
    $total .= 'pkj_query($sql,$parametros);' . "\n";
    $total .= "}\n";

// $total .= 'public function insertOrUpdate() {' . "\n";
// $total .= '$arquivos = $this->select();' . "\n";
// $total .= 'if (count($arquivos) > 0) {' . "\n";
// $total .= '  $this->update();' . "\n";
// $total .= '}else{' . "\n";
// $total .= '  $this->insert();' . "\n";
// $total .= "}\n";
// $total .= "}\n";

    $total .= "}\n ?>";
    return $total;
}

function download($arquivo, $mine = "") {
    $ext = explode(".", $arquivo);
    $ext = ((empty($ext[count($ext) - 1]) || count($ext) == 1) ? "" : $ext[count($ext) - 1]);
    switch ($ext) {
        case "pdf": $tipo = "application/pdf";
            break;
        case "exe": $tipo = "application/octet-stream";
            break;
        case "zip": $tipo = "application/zip";
            break;
        case "doc": $tipo = "application/msword";
            break;
        case "xls": $tipo = "application/vnd.ms-excel";
            break;
        case "ppt": $tipo = "application/vnd.ms-powerpoint";
            break;
        case "gif": $tipo = "image/gif";
            break;
        case "png": $tipo = "image/png";
            break;
        case "jpg": $tipo = "image/jpg";
            break;
        case "mp3": $tipo = "audio/mpeg";
            break;
    }
    if ($mine != ""):
        $tipo = $mine;
    endif;
    header("Content-Type: " . $tipo);
    header("Content-Length: " . filesize($arquivo));
    header("Content-Disposition: attachment; filename=" . basename($arquivo));
    readfile($arquivo);
    exit();
}

class Calendar {

    public static $FORMAT_BRASILEIRO_DATA = "brasileiro";
    public static $FORMAT_BRASILEIRO_DATA_HORA = "brasileiro completo";
    public static $FORMAT_AMERICANO_DATA = "americano";
    public static $FORMAT_AMERICANO_DATA_HORA = "americano completo";
    public $ano = "0000";
    public $mes = "00";
    public $dia = "00";
    public $hora = "00";
    public $minuto = "00";
    public $segundo = "00";
    public $semana = 1; //dia da semana

    function __construct($data = "") {
        if ($data == "") {
            $this->fromString(date('Y-m-d H:i:s'));
        } else {
            $this->fromString($data);
        }
    }

    function Calendar() {
        $this->fromString(date('Y-m-d H:i:s'));
    }

    public function modify($modificador) {
        $data = $this->toString("americano completo");
        $timestamp = strtotime($data . $modificador);
        $this->fromString(date('Y-m-d H:i:s', $timestamp));
    }

    public function format($format, $modify = '') {
        $data = $this->toString("americano completo");
        $timestamp = strtotime($data . $modify);
        return date($format, $timestamp);
    }

    public function addCalendar($calendario) {
        $data = $this->toString("americano completo");
        $timestamp = strtotime($data . "+{$calendario->ano} years {$calendario->mes} months {$calendario->dia} days {$calendario->hora} hours {$calendario->minuto} minutes {$calendario->segundo} seconds");
        $this->fromString(date('Y-m-d H:i:s', $timestamp));
    }

    public function removeCalendar($calendario) {
        $data = $this->toString("americano completo");
        $timestamp = strtotime($data . "-{$calendario->ano} years {$calendario->mes} months {$calendario->dia} days {$calendario->hora} hours {$calendario->minuto} minutes {$calendario->segundo} seconds");
        $this->fromString(date('Y-m-d H:i:s', $timestamp));
    }

    /**
     * 
     * @param type $formato americano, brasileiro, russo,americano completo, brasileiro completo, russo completo
     */
    public function toString($formato) {
        $retorno = "";
        switch ($formato) {
            case "americano":
                $retorno = "{$this->ano}-{$this->mes}-{$this->dia}";
                break;
            case "brasileiro":
                $retorno = "{$this->dia}/{$this->mes}/{$this->ano}";
                break;
            case "americano completo":
                $retorno = "{$this->ano}-{$this->mes}-{$this->dia} {$this->hora}:{$this->minuto}:{$this->segundo}";
                break;
            case "brasileiro completo":
                $retorno = "{$this->dia}/{$this->mes}/{$this->ano} {$this->hora}:{$this->minuto}:{$this->segundo}";
                break;
        }
        return $retorno;
    }

    public function fromString($data) {
        $separador = "";
        $separador = ((stripos($data, "-") > 0) ? "-" : $separador);
        $separador = ((stripos($data, "/") > 0) ? "/" : $separador);
        $separador = ((stripos($data, ".") > 0) ? "." : $separador);
        $dataOriginal = $data;
        $data = explode(" ", $data);
        $data = explode($separador, $data[0]);
        if ($separador == "/") {
            $this->dia = $this->completa(2, $data[0]);
        } else {
            $this->dia = $this->completa(2, $data[2]);
        }
        $this->mes = $this->completa(2, $data[1]);
        if ($separador == "/") {
            $this->ano = $data[2];
        } else {
            $this->ano = $data[0];
        }
        //$diasNoMes = cal_days_in_month(CAL_GREGORIAN, $this->mes, $this->ano);
        $this->semana = date("w", mktime(0, 0, 0, $this->mes, $this->dia, $this->ano));
        if (strlen(trim($dataOriginal)) > 10) {
            $this->hora = $this->completa(2, substr($dataOriginal, 11, 2));
            if (strlen(trim($dataOriginal)) > 13) {
                $this->minuto = $this->completa(2, substr($dataOriginal, 14, 2));
            }
            if (strlen(trim($dataOriginal)) > 16) {
                $this->segundo = $this->completa(2, substr($dataOriginal, 17, 2));
            }
        }
    }

    private function completa($casas, $valor) {
        $casasValor = strlen($valor);
        $zeros = "";
        for ($index = $casasValor; $index < $casas; $index++) {
            $zeros .= "0";
        }
        return ($zeros . "" . $valor);
    }

}

function lcase($texto) {
    return strtolower($texto);
}

function ucase($texto) {
    return strtoupper($texto);
}

function replace($texto, $procura, $valor) {
    return str_replace($procura, $valor, $texto);
}

function indexof($texto, $valor) {
    return find($texto, $valor);
}

function find($texto, $valor) {
    if (strpos($texto, $valor) === false) {
        return 0;
    } else {
        return strpos($texto, $valor) + 1;
    }
}

function len($texto) {
    return strlen($texto);
}

function substring($texto, $inicio, $quantidade = -1) {
    if ($quantidade == -1) {
        $quantidade = len($texto) - $inicio;
    }
    return substr($texto, $inicio, $quantidade);
}

function part($texto, $separador) {
    return explode($separador, $texto);
}

function get($campo) {
    $retorno = "";
    if (isset($_GET[$campo])) {
        $retorno = $_GET[$campo];
    }
    return $retorno;
}

function post($campo) {
    $retorno = "";
    if (isset($_POST[$campo])) {
        $retorno = $_POST[$campo];
    }
    return $retorno;
}

function addslashes_array(&$arr_r) {
    if (is_array($arr_r)) {
        foreach ($arr_r as &$val) {
            is_array($val) ? addslashes_array($val) : $val = str_replace("'", '', $val);
        }
        unset($val);
    } else {
        $arr_r = str_replace("'", "", $arr_r);
    }
}

//function addslashes_array($a) {
//    if (is_array($a)) {
//        foreach ($a as $n => $v) {
//            $b[$n] = addslashes_array($v);
//        }
//    } else {
//        return addslashes($a);
//    }
//    return $b;
//}

function addslashes_deep($input) {
    return addslashes_array($input);
}

function castBoolean($value) {
    return (ucase($value) == "TRUE") ? true : false;
}
?>
